//
// Created by bjliuyong on 2021/6/20.
//
#include "mark_copy.h"

MarkCopy::MarkCopy(MemoryChunk *memoryChunk) {
    this->m_mem_chunk = memoryChunk;
}


MarkCopy::~MarkCopy() {
}

void MarkCopy::run() {
    mark();
    memory_sweep();
}


void MarkCopy::mark() {
    PRINT("\t 开始执行标记操作\n");

    /**
     * 模拟可达性分析算法标记对象，回收未打标记的对象
     */
    list<MemoryCell *> *used_table = m_mem_chunk->get_used_table();

    list<MemoryCell *>::iterator iterator;
    for (iterator = used_table->begin(); iterator != used_table->end(); iterator++) {
        MemoryCell *cell = *iterator;

        if (4 == cell->get_size() || 1 == cell->get_size()) {
            INFO_PRINT("\t 打上标记\n");

            (*iterator)->set_mark(true);
        } else {
            INFO_PRINT("\t 未打标记\n");
        }
    }
}

void MarkCopy::memory_sweep() {
    this->m_mem_chunk->renew_cell_start();
    m_mem_chunk->free_available_table();

    m_mem_chunk->set_used_cell_num(0);
    /* MemoryCell *c = m_mem_chunk->get_idle_table()->front();
     m_mem_chunk->get_available_table()->push_front(c);

     m_mem_chunk->get_idle_table()->pop_front();*/

    m_mem_chunk->set_available_table(*(m_mem_chunk->get_idle_table()));

    m_mem_chunk->get_idle_table()->pop_front();
    m_mem_chunk->get_idle_table()->push_front(
            new MemoryCell(m_mem_chunk->get_new_cell_start(), m_mem_chunk->get_cell_num() / 2));

    for (list<MemoryCell *>::iterator itr = m_mem_chunk->get_used_table()->begin();
         itr != m_mem_chunk->get_used_table()->end(); ) {

        MemoryCell *c = *itr;
        if (!c->get_mark()) {
            INFO_PRINT("\t 未打标记，开始释放资源\n");
            itr =  m_mem_chunk->get_used_table()->erase(itr);
            delete c;
        } else {
            INFO_PRINT("\t 打了标记，开始处理\n");

            m_mem_chunk->malloc_after_gc(c);
            itr++;
        }
    }

}